<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>多人迷宫探险</title>
    <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=Roboto:wght@400;700&display=swap" rel="stylesheet">
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Roboto', sans-serif;
            background: linear-gradient(135deg, #1a2a6c, #b21f1f, #1a2a6c);
            color: #fff;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
            overflow-x: hidden;
        }

        .container {
            width: 100%;
            max-width: 1200px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        header {
            text-align: center;
            padding: 20px 0;
            margin-bottom: 20px;
            width: 100%;
        }

        h1 {
            font-family: 'Press Start 2P', cursive;
            font-size: 2.5rem;
            color: #ffcc00;
            text-shadow: 3px 3px 0 #ff6b00, 5px 5px 0 rgba(0, 0, 0, 0.2);
            margin-bottom: 15px;
            letter-spacing: 2px;
        }

        .subtitle {
            font-size: 1.2rem;
            color: #ffdd99;
            max-width: 800px;
            margin: 0 auto 20px;
            line-height: 1.6;
        }

        .game-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 30px;
            width: 100%;
            margin-bottom: 30px;
        }

        .maze-section {
            flex: 1;
            min-width: 500px;
            background: rgba(0, 0, 0, 0.7);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
        }

        .controls-section {
            width: 300px;
            background: rgba(0, 0, 0, 0.7);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
        }

        .section-title {
            font-size: 1.5rem;
            color: #4dabf7;
            margin-bottom: 20px;
            text-align: center;
            font-weight: bold;
        }

        .maze-grid {
            display: grid;
            grid-template-columns: repeat(15, 1fr);
            gap: 2px;
            width: 100%;
            aspect-ratio: 1/1;
            background: #444;
            border: 3px solid #ff6b00;
            border-radius: 5px;
            overflow: hidden;
            position: relative;
        }

        .cell {
            background: #333;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background-color 0.3s;
            position: relative;
        }

        .cell.wall {
            background: #1a237e;
        }

        .cell.path {
            background: #222;
        }

        .cell.start {
            background: #4caf50;
        }

        .cell.end {
            background: #f44336;
        }

        .cell.player {
            position: relative;
            z-index: 10;
        }

        .player-marker {
            position: absolute;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 10px;
            z-index: 20;
            box-shadow: 0 0 5px rgba(0,0,0,0.5);
            transition: transform 0.2s;
        }

        .player-marker.active {
            transform: scale(1.2);
            box-shadow: 0 0 8px white;
            z-index: 30;
        }

        .player-1 { background: #ffeb3b; color: #000; top: 5px; left: 5px; }
        .player-2 { background: #2196F3; color: #fff; top: 5px; right: 5px; }
        .player-3 { background: #4CAF50; color: #fff; bottom: 5px; left: 5px; }
        .player-4 { background: #9C27B0; color: #fff; bottom: 5px; right: 5px; }

        .cell.visited {
            background: rgba(76, 175, 80, 0.3);
        }

        .btn {
            display: block;
            width: 100%;
            padding: 15px;
            margin: 15px 0;
            font-size: 1.1rem;
            font-weight: bold;
            color: white;
            background: linear-gradient(to right, #ff6b00, #ffcc00);
            border: none;
            border-radius: 50px;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 5px 15px rgba(255, 107, 0, 0.4);
        }

        .btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(255, 107, 0, 0.6);
        }

        .btn:active {
            transform: translateY(1px);
        }

        .btn.secondary {
            background: linear-gradient(to right, #4a69bd, #6a89cc);
        }

        .stats {
            background: rgba(0, 0, 0, 0.5);
            border-radius: 10px;
            padding: 15px;
            margin: 15px 0;
            text-align: center;
        }

        .stat-value {
            font-size: 1.8rem;
            font-weight: bold;
            color: #ffcc00;
            margin: 10px 0;
        }

        .stat-label {
            font-size: 1rem;
            color: #aaa;
        }

        .instructions {
            background: rgba(0, 0, 0, 0.5);
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
        }

        .instructions h3 {
            color: #4dabf7;
            margin-bottom: 15px;
        }

        .instructions ul {
            padding-left: 20px;
        }

        .instructions li {
            margin-bottom: 10px;
            line-height: 1.5;
        }

        .key-controls {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            margin-top: 20px;
        }

        .key {
            background: rgba(255, 255, 255, 0.1);
            border: 2px solid #ffcc00;
            border-radius: 10px;
            padding: 15px;
            text-align: center;
            font-weight: bold;
        }

        .difficulty-controls {
            display: flex;
            justify-content: space-between;
            margin: 20px 0;
        }

        .difficulty-btn {
            padding: 10px 15px;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid #4dabf7;
            border-radius: 5px;
            color: white;
            cursor: pointer;
            transition: all 0.3s;
        }

        .difficulty-btn.active {
            background: #4dabf7;
            font-weight: bold;
        }

        .player-controls {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }

        .player-btn {
            width: 22%;
            padding: 8px;
            border-radius: 8px;
            background: rgba(255,255,255,0.1);
            border: 2px solid #666;
            color: white;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: bold;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .player-btn.active {
            border-color: #ffcc00;
            background: rgba(255,204,0,0.2);
        }

        .player-btn .player-indicator {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            margin-bottom: 5px;
        }

        .player-btn-1 .player-indicator { background: #ffeb3b; }
        .player-btn-2 .player-indicator { background: #2196F3; }
        .player-btn-3 .player-indicator { background: #4CAF50; }
        .player-btn-4 .player-indicator { background: #9C27B0; }

        @media (max-width: 900px) {
            .game-container {
                flex-direction: column;
                align-items: center;
            }

            .maze-section {
                min-width: 100%;
            }

            .controls-section {
                width: 100%;
            }

            h1 {
                font-size: 1.8rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>多人迷宫探险</h1>
            <p class="subtitle">控制四个玩家从起点到达终点！使用方向键移动当前玩家，数字键1-4切换玩家。当前玩家：<span id="current-player-display">{{ user_id }}</span></p>
        </header>

        <div class="game-container">
            <div class="maze-section">
                <h2 class="section-title">迷宫区域</h2>
                <div class="maze-grid" id="maze"></div>
            </div>

            <div class="controls-section">
                <h2 class="section-title">游戏控制</h2>

                <div class="player-controls">
                    <div class="player-btn player-btn-1" data-player="1">
                        <div class="player-indicator"></div>
                        <a href="{% url 'Labyrinth_app:generate_id' user_id=1 %}">
                            <div>玩家 1 </div>
                        </a>
                    </div>
                    <div class="player-btn player-btn-2" data-player="2">
                        <div class="player-indicator"></div>
                        <a href="{% url 'Labyrinth_app:generate_id' user_id=2 %}">
                            <div>玩家 2 </div>
                        </a>
                    </div>
                    <div class="player-btn player-btn-3" data-player="3">
                        <div class="player-indicator"></div>
                        <a href="{% url 'Labyrinth_app:generate_id' user_id=3 %}">
                            <div>玩家 3 </div>
                        </a>
                    </div>
                    <div class="player-btn player-btn-4" data-player="4">
                        <div class="player-indicator"></div>
                        <a href="{% url 'Labyrinth_app:generate_id' user_id=4 %}">
                            <div>玩家 4 </div>
                        </a>
                    </div>
                </div>

                <div class="difficulty-controls">
                    <div class="difficulty-btn active" data-size="15">简单</div>
                    <div class="difficulty-btn" data-size="25">中等</div>
                    <div class="difficulty-btn" data-size="35">困难</div>
                </div>

                <button class="btn" id="generateBtn">生成新迷宫</button>
                <button class="btn secondary" id="solveBtn">显示解决方案</button>
                <button class="btn" id="resetBtn">重置玩家位置</button>

                <div class="stats">
                    <div class="stat-label">当前时间</div>
                    <div class="stat-value" id="timer">00:00</div>
                </div>

                <div class="stats">
                    <div class="stat-label">最佳时间</div>
                    <div class="stat-value" id="bestTime">00:00</div>
                </div>

                <div class="key-controls">
                    <div class="key">W / ↑</div>
                    <div class="key">A / ←</div>
                    <div class="key">D / →</div>
                    <div class="key">S / ↓</div>
                    <div class="key">1-4</div>
                    <div class="key">切换玩家</div>
                    <div class="key">空格</div>
                    <div class="key">生成</div>
                    <div class="key">新迷宫</div>
                </div>
            </div>
        </div>

        <div class="instructions">
            <h3>游戏说明</h3>
            <ul>
                <li>使用<strong>方向键</strong>或<strong>WASD键</strong>移动<strong>当前玩家</strong></li>
                <li>按<strong>数字键1-4</strong>或点击上方玩家按钮切换当前玩家</li>
                <li>从<strong style="color:#4caf50">绿色起点</strong>出发，到达<strong style="color:#f44336">红色终点</strong></li>
                <li>所有玩家都需要到达终点才能获胜</li>
                <li>按<strong>空格键</strong>或点击"生成新迷宫"按钮创建新的随机迷宫</li>
                <li>游戏会自动记录你的最佳完成时间</li>
                <li>选择不同难度级别改变迷宫大小</li>
            </ul>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // 游戏配置
            const config = {
                mazeSize: 15,
                players: [
                    {id: 1, x: 1, y: 1, color: '#ffeb3b', completed: false},
                    {id: 2, x: 1, y: 1, color: '#2196F3', completed: false},
                    {id: 3, x: 1, y: 1, color: '#4CAF50', completed: false},
                    {id: 4, x: 1, y: 1, color: '#9C27B0', completed: false}
                ],
                currentPlayerId: {{ user_id }},
                end: {x: 0, y: 0},
                timer: 0,
                timerInterval: null,
                bestTime: localStorage.getItem('mazeBestTime') || 0,
                isSolving: false
            };

            // DOM元素
            const mazeElement = document.getElementById('maze');
            const generateBtn = document.getElementById('generateBtn');
            const solveBtn = document.getElementById('solveBtn');
            const resetBtn = document.getElementById('resetBtn');
            const timerElement = document.getElementById('timer');
            const bestTimeElement = document.getElementById('bestTime');
            const difficultyBtns = document.querySelectorAll('.difficulty-btn');
            const playerBtns = document.querySelectorAll('.player-btn');
            const currentPlayerDisplay = document.getElementById('current-player-display');

            // 初始化游戏
            function initGame() {
                generateMaze();
                updateBestTimeDisplay();
                document.addEventListener('keydown', handleKeyPress);
                generateBtn.addEventListener('click', generateMaze);
                solveBtn.addEventListener('click', toggleSolveMaze);
                resetBtn.addEventListener('click', resetPlayers);

                difficultyBtns.forEach(btn => {
                    btn.addEventListener('click', () => {
                        difficultyBtns.forEach(b => b.classList.remove('active'));
                        btn.classList.add('active');
                        config.mazeSize = parseInt(btn.dataset.size);
                        generateMaze();
                    });
                });
                playerBtns.forEach(btn => {
                    btn.addEventListener('click', () => {
                        const playerId = parseInt(btn.dataset.player);
                        switchPlayer(playerId);
                    });
                });
            }

            // 切换当前玩家
            function switchPlayer(playerId) {
                config.currentPlayerId = playerId;
                currentPlayerDisplay.textContent = playerId;

                // 更新UI
                playerBtns.forEach(btn => {
                    if (parseInt(btn.dataset.player) === playerId) {
                        btn.classList.add('active');
                    } else {
                        btn.classList.remove('active');
                    }
                });

                renderMaze();
            }

            // 生成迷宫
            function generateMaze() {
                // 重置游戏状态
                clearInterval(config.timerInterval);
                config.timer = 0;
                updateTimerDisplay();

                // 重置玩家状态
                config.players.forEach(player => {
                    player.completed = false;
                });

                // 创建迷宫数据结构
                const size = config.mazeSize;
                const maze = [];

                // 初始化迷宫（全部为墙）
                for (let y = 0; y < size; y++) {
                    const row = [];
                    for (let x = 0; x < size; x++) {
                        row.push(1); // 1表示墙
                    }
                    maze.push(row);
                }

                // 使用深度优先搜索生成迷宫路径
                carvePaths(maze, 1, 1, size);

                // 设置起点和终点
                maze[1][1] = 2; // 起点
                maze[size-2][size-2] = 3; // 终点

                // 保存迷宫和重置玩家位置
                config.maze = maze;
                config.players.forEach(player => {
                    player.x = 1;
                    player.y = 1;
                    player.completed = false;
                });
                config.end = {x: size-2, y: size-2};
                config.isSolving = false;

                // 渲染迷宫
                renderMaze();
            }

            // 使用深度优先算法生成迷宫路径
            function carvePaths(maze, x, y, size) {
                // 四个方向：上、右、下、左
                const directions = [
                    [0, -2], [2, 0], [0, 2], [-2, 0]
                ];

                // 随机打乱方向顺序
                shuffleArray(directions);

                maze[y][x] = 0; // 标记为路径

                // 探索每个方向
                for (const [dx, dy] of directions) {
                    const nx = x + dx;
                    const ny = y + dy;

                    // 检查是否在边界内
                    if (nx > 0 && nx < size-1 && ny > 0 && ny < size-1 && maze[ny][nx] === 1) {
                        // 打通墙壁
                        maze[y + dy/2][x + dx/2] = 0;
                        carvePaths(maze, nx, ny, size);
                    }
                }
            }

            // Fisher-Yates洗牌算法
            function shuffleArray(array) {
                for (let i = array.length - 1; i > 0; i--) {
                    const j = Math.floor(Math.random() * (i + 1));
                    [array[i], array[j]] = [array[j], array[i]];
                }
            }

            // 渲染迷宫到DOM
            function renderMaze() {
                mazeElement.innerHTML = '';
                mazeElement.style.gridTemplateColumns = `repeat(${config.mazeSize}, 1fr)`;

                for (let y = 0; y < config.mazeSize; y++) {
                    for (let x = 0; x < config.mazeSize; x++) {
                        const cell = document.createElement('div');
                        cell.classList.add('cell');

                        // 添加对应的类
                        if (config.maze[y][x] === 1) {
                            cell.classList.add('wall');
                        } else {
                            cell.classList.add('path');
                        }

                        if (x === 1 && y === 1) {
                            cell.classList.add('start');
                        }

                        if (x === config.end.x && y === config.end.y) {
                            cell.classList.add('end');
                        }

                        // 检查此单元格是否有玩家
                        const playersHere = config.players.filter(p => p.x === x && p.y === y);

                        // 如果有玩家，添加玩家标记
                        playersHere.forEach(player => {
                            const playerMarker = document.createElement('div');
                            playerMarker.classList.add('player-marker', `player-${player.id}`);
                            playerMarker.textContent = player.id;
                            if (player.id === config.currentPlayerId) {
                                playerMarker.classList.add('active');
                            }
                            cell.appendChild(playerMarker);
                            cell.classList.add('player');
                        });

                        mazeElement.appendChild(cell);
                    }
                }
            }

            // 处理键盘事件
            function handleKeyPress(e) {
                // 空格键生成新迷宫
                if (e.key === ' ' || e.key === 'Spacebar') {
                    generateMaze();
                    return;
                }

                // R键重置玩家位置
                if (e.key === 'r' || e.key === 'R') {
                    resetPlayers();
                    return;
                }

                // 数字键1-4切换玩家
                if (e.key >= '1' && e.key <= '4') {
                    const playerId = parseInt(e.key);
                    switchPlayer(playerId);
                    return;
                }

                let dx = 0, dy = 0;

                // 方向键和WASD控制
                if (e.key === 'ArrowUp' || e.key === 'w' || e.key === 'W') dy = -1;
                if (e.key === 'ArrowRight' || e.key === 'd' || e.key === 'D') dx = 1;
                if (e.key === 'ArrowDown' || e.key === 's' || e.key === 'S') dy = 1;
                if (e.key === 'ArrowLeft' || e.key === 'a' || e.key === 'A') dx = -1;

                // 如果有移动方向
                if (dx !== 0 || dy !== 0) {
                    movePlayer(dx, dy);
                }
            }

            // 移动玩家
            function movePlayer(dx, dy) {
                const player = config.players.find(p => p.id === config.currentPlayerId);
                if (!player || player.completed) return;

                const newX = player.x + dx;
                const newY = player.y + dy;

                // 检查是否可以移动（在边界内且不是墙）
                if (newX >= 0 && newX < config.mazeSize &&
                    newY >= 0 && newY < config.mazeSize &&
                    config.maze[newY][newX] !== 1) {

                    // 启动计时器（如果尚未启动）
                    if (!config.timerInterval) {
                        startTimer();
                    }

                    // 更新玩家位置
                    player.x = newX;
                    player.y = newY;

                    // 重新渲染迷宫
                    renderMaze();

                    // 检查是否到达终点
                    if (newX === config.end.x && newY === config.end.y) {
                        player.completed = true;

                        // 检查是否所有玩家都已完成
                        if (config.players.every(p => p.completed)) {
                            finishGame();
                        } else {
                            // 提示当前玩家已完成
                            const playerBtn = document.querySelector(`.player-btn[data-player="${player.id}"]`);
                            playerBtn.style.borderColor = '#4CAF50';
                            playerBtn.style.background = 'rgba(76, 175, 80, 0.3)';

                            // 自动切换到下一个未完成的玩家
                            const nextPlayer = config.players.find(p => !p.completed);
                            if (nextPlayer) {
                                switchPlayer(nextPlayer.id);
                            }
                        }
                    }
                }
            }

            // 重置玩家位置
            function resetPlayers() {
                config.players.forEach(player => {
                    player.x = 1;
                    player.y = 1;
                    player.completed = false;
                });

                // 重置玩家按钮样式
                playerBtns.forEach(btn => {
                    btn.style.borderColor = '';
                    btn.style.background = '';
                });

                renderMaze();

                // 重置计时器
                clearInterval(config.timerInterval);
                config.timer = 0;
                updateTimerDisplay();
                config.timerInterval = null;
            }

            // 开始计时
            function startTimer() {
                config.timerInterval = setInterval(() => {
                    config.timer++;
                    updateTimerDisplay();
                }, 1000);
            }

            // 更新计时器显示
            function updateTimerDisplay() {
                const minutes = Math.floor(config.timer / 60).toString().padStart(2, '0');
                const seconds = (config.timer % 60).toString().padStart(2, '0');
                timerElement.textContent = `${minutes}:${seconds}`;
            }

            // 更新最佳时间显示
            function updateBestTimeDisplay() {
                if (config.bestTime > 0) {
                    const minutes = Math.floor(config.bestTime / 60).toString().padStart(2, '0');
                    const seconds = (config.bestTime % 60).toString().padStart(2, '0');
                    bestTimeElement.textContent = `${minutes}:${seconds}`;
                } else {
                    bestTimeElement.textContent = "00:00";
                }
            }

            // 完成游戏
            function finishGame() {
                clearInterval(config.timerInterval);

                // 更新最佳时间
                if (config.bestTime === 0 || config.timer < config.bestTime) {
                    config.bestTime = config.timer;
                    localStorage.setItem('mazeBestTime', config.bestTime);
                    updateBestTimeDisplay();

                    // 显示庆祝消息
                    alert(`恭喜！所有玩家以${timerElement.textContent}的成绩完成了迷宫！新记录！`);
                } else {
                    alert(`恭喜！所有玩家以${timerElement.textContent}的成绩完成了迷宫！`);
                }
            }

            // 切换显示解决方案
            function toggleSolveMaze() {
                config.isSolving = !config.isSolving;
                solveBtn.textContent = config.isSolving ? '隐藏解决方案' : '显示解决方案';

                if (config.isSolving) {
                    solveMaze();
                } else {
                    renderMaze();
                }
            }

            // 解决迷宫（使用广度优先搜索）
            function solveMaze() {
                const size = config.mazeSize;
                const queue = [{x: 1, y: 1, path: []}];
                const visited = new Set();
                visited.add('1,1');

                while (queue.length > 0) {
                    const {x, y, path} = queue.shift();

                    // 到达终点
                    if (x === config.end.x && y === config.end.y) {
                        // 高亮显示路径
                        for (const [px, py] of path) {
                            const index = py * size + px;
                            mazeElement.children[index].classList.add('visited');
                        }
                        return;
                    }

                    // 探索四个方向
                    const directions = [[0, -1], [1, 0], [0, 1], [-1, 0]];
                    for (const [dx, dy] of directions) {
                        const nx = x + dx;
                        const ny = y + dy;
                        const key = `${nx},${ny}`;

                        // 检查是否可移动且未访问过
                        if (nx >= 0 && nx < size && ny >= 0 && ny < size &&
                            config.maze[ny][nx] !== 1 && !visited.has(key)) {

                            visited.add(key);
                            queue.push({
                                x: nx,
                                y: ny,
                                path: [...path, [x, y]]
                            });
                        }
                    }
                }
            }

            // 初始化游戏
            initGame();
        });
    </script>
</body>
</html>